<template>
  <div class="update-photo">
      <img
        ref="image"
        class="image" 
        :src="image" >
      <van-nav-bar
      class="tarbar"
        left-text='取消'
        right-text="确定"
        @click-left="$emit('close')"
        @click-right="onComfirm"
      >
      </van-nav-bar>
  </div>
</template>

<script>
import { updateUserPhoto } from '@/api/user'
import 'cropperjs/dist/cropper.css'
import Cropper from 'cropperjs'

export default {
  name: 'UpdatePhoto',
  components: {},
  props: {
      file: {
        //   type: String,
          require: true
      }
  },
  data() {
    return {
        image: window.URL.createObjectURL(this.file),
        cropper: null // 裁剪器实例
    };
  },
  computed: {},
  watch: {},
  created() {},
  mounted() {
    const image = this.$refs.image
    this.cropper = new Cropper(image, {
        viewMode: 1,
        dragMode: 'move',
        aspectRatio: 1,
        autoCropArea: 1,
        cropBoxMovable: false,
        cropBoxResizable: false,
        background: false,
        movable: true
    });
    // console.log(cropper);
  },
  methods: {
      getCroppedCanvas() {
          return new Promise(resolve => {
              this.cropper.getCroppedCanvas().toBlob((blob) => {
                resolve(blob)
              })
          })
      },
      async onComfirm() {
          this.$toast.loading({
              message: '保存中',
              forbidClick: true,
              duration: 0
          })
          // 如果要求 Content-Type 是 multipart/form-data，则一定要提交 FormData 数据对象，专门用于文件上传，不能提交 {}，没用
        //   const fd = new FormData()
        //   fd.append('photo', this.file)
          const file = await this.getCroppedCanvas()
          const fd = new FormData()
          fd.append('photo', file)
          await updateUserPhoto(fd)

          // 更新父组件的图片
          this.$emit('update-photo', window.URL.createObjectURL(file))

          this.$toast.success('保存成功')

          // 关闭弹出层
          this.$emit('close')
      }
  }
};
</script>
<style lang="less" scoped>
.tarbar {
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: #000;
    color: #fff;
    /deep/ .van-nav-bar__text {
        color: #fff;
    }
}
/* Ensure the size of the image fit the container perfectly */
.img {
  display: block;

  /* This rule is very important, please don't ignore this */
  max-width: 100%;
}
</style>